program define estimate_IRF_external_IV, eclass
	
	syntax varlist(min = 3 max = 3), [L(int 8) K(int 4) ///
		min_lags_NW(int 4) Alpha(real 0.05)] 
	args dep_var indep_var inst_var
	
	* Create matrices for storing results
	tempvar res
	matrix `res' = J(`l', 8, .)
	matrix colnames `res'  = lag IRF se lb ub df_resid K F_stat
	
	* Create temporary variables containing lags and leads
	quietly {
		forvalues ll = 1/`k' {
			tempvar `dep_var'_LAG`ll'
			tempvar `indep_var'_LAG`ll'
			tempvar `inst_var'_LAG`ll'
			gen ``dep_var'_LAG`ll'' = l`ll'.`dep_var'
			gen ``indep_var'_LAG`ll'' = l`ll'.`indep_var'
			gen ``inst_var'_LAG`ll'' = l`ll'.`inst_var'
		} 
		forvalues ll = 0/`l' {
			tempvar `dep_var'_LEAD`ll'
			gen ``dep_var'_LEAD`ll'' = f`ll'.`dep_var'
		}	
	}
	
	* Construct controls of the regression
	local controls
	forvalues ll = 1/`k' {
		local controls `controls' ``dep_var'_LAG`ll''
	}
	forvalues ll = 2/`k' {
		local controls `controls' ``indep_var'_LAG`ll''
	}
	
	* Calculate local projections
	forvalues ii = 1/`l' {
		local ii_1 = `ii' - 1
		local lags_NW = max(`min_lags_NW', `ii_1')
		
		* Main regression
		quietly ivreg2 ``dep_var'_LEAD`ii_1'' /// 
			`controls' (``indep_var'_LAG1' = ``inst_var'_LAG1'), ///  
			robust bw(`lags_NW') small
		
		* Collect the results and calculate 
		* confidence intervals at the given significance level
		local se = _se[``indep_var'_LAG1']
		local df_r = e(df_r)
		local t_crit = invt(`df_r', `alpha' / 2)
		
		matrix `res' [`ii', 1] = `ii'
		matrix `res' [`ii', 2] = _b[``indep_var'_LAG1']
		matrix `res' [`ii', 3] = `se'
		matrix `res' [`ii', 4] = _b[``indep_var'_LAG1'] + ///
			`t_crit' * `se'
		matrix `res' [`ii', 5] = _b[``indep_var'_LAG1'] - ///
			`t_crit' * `se'
		matrix `res' [`ii', 6] = `df_r'
		matrix `res' [`ii', 7] = `k'
		matrix `res' [`ii', 8] = e(widstat)
	}
	
	ereturn matrix s `res'

end 
